<div class="grid_4 alpha">
	<h3 class="title">Lista mail</h3>

	<div class="options-wrapper">
		<ul class="options-holder left">
			<li class="option check" id="check-all"><span>zaznacz</span></li>
			<li class="option uncheck" id="check-none"><span>odznacz</span></li>
		</ul>
		
		<ul class="options-holder right">
			<li class="option refresh" id="mail-reload"><a href="#">Odświerz</a></li>
		</ul>
	</div>

	<div style="overflow: auto; height: 500px">
		<ul id="mail-list"></ul>
	</div>
</div>
<div class="grid_4">
	<h3 class="title">Szablon</h3>
	
	<div class="options-wrapper">		
		<ul class="options-holder right">
			<li class="option refresh" id="mail-template-reload"><a href="#">Odświerz</a></li>
		</ul>
	</div>
	
	<div style="overflow: auto; height: 500px">
		<ul id="mail-template-list"></ul>
	</div>
</div>
<div class="grid_8 omega">
	<h3 class="title">Informacje</h3>
	
	<div class="options-wrapper">
		<ul class="options-holder left">
			<li class="option"><span>Wysłane wiadomości: <em id="mail-send">0</em> z <em id="mail-all">0</em></span></li>
			<li class="option"><span>Rozsyłaj po: <input type="text" value="4" id="intervalSend" class="text ui-widget-content ui-corner-all" style="width: 20px;"/> maile</span></li>
		</ul>

		<ul class="options-holder right">
			<li class="option reset"><a href="#">Wyczyść</a></li>
			<li class="option send-mails"><a href="#">Wyślij wiadomości</a></li>
		</ul>
	</div>

	<div id="dialog">
		<div id="progressbar"></div>
	</div>
	
	<div class="grid_4 alpha">
		<dl>
			<dt>Temat wiadomości</dt>
			<dt><input type="text" name="subject" class="text ui-widget-content ui-corner-all"/></dt>
			<dt>Nazwa nadawcy</dt>
			<dt><input type="text" name="sender_name" class="text ui-widget-content ui-corner-all"/></dt>
			<dt>Adress e-mail</dt>
			<dt><input type="text" name="sender" class="text ui-widget-content ui-corner-all"/></dt>
		</dl>
	</div>
	<div class="grid_4 omega">
		<dl>
			<dt>Treść wiadomości</dt>
			<dt><textarea name="content" rows="7" style="width: 100%" class="text ui-widget-content ui-corner-all"></textarea></dt>
		</dl>
	</div>
</div>

<div class="clear"></div>

<?php /* @var $inlineScript Zend_View_Helper_InlineScript */
//      $inlineScript = $this->getHelper('inlineScript');
//      $inlineScript->setOffsetFile();
?>

<script type="text/javascript"><!--
function urlencode (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer
    // +      input by: Ratheous
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: This reflects PHP 5.3/6.0+ behavior
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
 
    var hexStr = function (dec) {
        return '%' + dec.toString(16).toUpperCase();
    };
 
    var ret = '',
            unreserved = /[\w.-]/; // A-Za-z0-9_.- // Tilde is not here for historical reasons; to preserve it, use rawurlencode instead
    str = (str+'').toString();
 
    for (var i = 0, dl = str.length; i < dl; i++) {
        var ch = str.charAt(i);
        if (unreserved.test(ch)) {
            ret += ch;
        }
        else {
            var code = str.charCodeAt(i);
            // Reserved assumed to be in UTF-8, as in PHP
            if (code === 32) {
                ret += '+'; // %20 in rawurlencode
            }
            else if (code < 128) { // 1 byte
                ret += hexStr(code);
            }
            else if (code >= 128 && code < 2048) { // 2 bytes
                ret += hexStr((code >> 6) | 0xC0);
                ret += hexStr((code & 0x3F) | 0x80);
            }
            else if (code >= 2048 && code < 65536) { // 3 bytes
                ret += hexStr((code >> 12) | 0xE0);
                ret += hexStr(((code >> 6) & 0x3F) | 0x80);
                ret += hexStr((code & 0x3F) | 0x80);
            }
            else if (code >= 65536) { // 4 bytes
                ret += hexStr((code >> 18) | 0xF0);
                ret += hexStr(((code >> 12) & 0x3F) | 0x80);
                ret += hexStr(((code >> 6) & 0x3F) | 0x80);
                ret += hexStr((code & 0x3F) | 0x80);
            }
        }
    }
    return ret;
}
function http_build_query (formdata, numeric_prefix, arg_separator) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Legaev Andrey
    // +   improved by: Michael White (http://getsprink.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: stag019
    // -    depends on: urlencode
    // *     example 1: http_build_query({foo: 'bar', php: 'hypertext processor', baz: 'boom', cow: 'milk'}, '', '&amp;');
    // *     returns 1: 'foo=bar&amp;php=hypertext+processor&amp;baz=boom&amp;cow=milk'
    // *     example 2: http_build_query({'php': 'hypertext processor', 0: 'foo', 1: 'bar', 2: 'baz', 3: 'boom', 'cow': 'milk'}, 'myvar_');
    // *     returns 2: 'php=hypertext+processor&myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&cow=milk'
 
    var value, key, tmp = [];
 
    var _http_build_query_helper = function (key, val, arg_separator) {
        var k, tmp = [];
        if (val === true) {
            val = "1";
        } else if (val === false) {
            val = "0";
        }
        if (typeof(val) == "array" || typeof(val) == "object") {
            for (k in val) {
                if (val[k] !== null) {
                    tmp.push(_http_build_query_helper(key + "[" + k + "]", val[k], arg_separator));
                }
            }
            return tmp.join(arg_separator);
        } else if (typeof(val) != "function") {
            return urlencode(key) + "=" + urlencode(val);
        }
    };
 
    if (!arg_separator) {
        arg_separator = "&";
    }
    for (key in formdata) {
        value = formdata[key];
        if (numeric_prefix && !isNaN(key)) {
            key = String(numeric_prefix) + key;
        }
        tmp.push(_http_build_query_helper(key, value, arg_separator));
    }
 
    return tmp.join(arg_separator);
}

(function($){
var Mailer = {
	url_send: '/mail/send/queue/format/json',
	url_mail: '/mail/mail/list/format/json',
	url_template: '/mail/template/list/format/json',

	selector_mail_list: '#mail-list',
	
	selector_template_list: '#mail-template-list',
	selector_template_bind_sender: 'input[name=sender]',
	selector_template_bind_sender_name: 'input[name=sender_name]',
	selector_template_bind_subject: 'input[name=subject]',
	selector_template_bind_content: 'textarea[name=content]',

	selector_mail_send: '#mail-send',
	selector_mail_count: '#mail-all',

	selector_progressbar: '#progressbar',

	init: function() {
		this.initMail();
		this.initTemplate();
	},

	initMail: function() {
		$.ajax({
			url: Mailer.url_mail,
			dataType: 'json',
			success: Mailer.onSuccessMail
		});
	},

	onSuccessMail: function(json) {
		var mailList = $(Mailer.selector_mail_list);
		mailList.find('li').remove();

		$(json).each(function(k, item){
			var mailItem = Mailer.createMailItem(item);
			mailList.append($('<li/>').append(mailItem));
		});
	},

	createMailItem: function(item) {
		var radio = $('<input type="checkbox" name="email[]" value="" />')
			.val(item.email);

		return $('<label />')
			.append(radio)
			.append(!item.name ? item.email : item.name)
			.click(function(){
				Mailer.bindTemplate(item);
			});
	},
	
	initTemplate: function() {
		$.ajax({
			url: Mailer.url_template,
			dataType: 'json',
			success: Mailer.onSuccessTemplate
		});
	},

	onSuccessTemplate: function(json) {
		var mailList = $(Mailer.selector_template_list);
		mailList.find('li').remove();

		$(json).each(function(k, item) {
			var templateItem = Mailer.createTemplateItem(item);
			mailList.append($('<li/>').append(templateItem));
		});
	},

	createTemplateItem: function(item) {
		var radio = $('<input type="radio" name="template" value="" />')
			.val(item.id);

		return $('<label />')
			.append(radio)
			.append(item.name)
			.click(function(){
				Mailer.bindTemplate(item);
			});
	},

	bindTemplate: function(item) {
		$(Mailer.selector_template_bind_sender).val(item.sender);
		$(Mailer.selector_template_bind_sender_name).val(item.sender_name);
		$(Mailer.selector_template_bind_subject).val(item.subject);
		$(Mailer.selector_template_bind_content).val(item.content);
		
		return false;
	},

	clear: function() {
		this._count = 0;
		this._send = 0;
		this._start = 0;
		this._sended = true;
		this._interval = null;
		this._stoped = false;
	},

	clearData: function () {
		this.clearSender();
		this.clearSenderName();
		this.clearSubject();
		this.clearContent();
		this.clearSend();
		this.clearCount();
	},

	setSender: function(sender){
		$(Mailer.selector_template_bind_sender).val(sender);
	},
	
	getSender: function(){
		return $(Mailer.selector_template_bind_sender).val();
	},

	clearSender: function(){
		this.setSender('');
	},

	setSenderName: function(name){
		$(Mailer.selector_template_bind_sender_name).val(name);
	},
	
	getSenderName: function(){
		return $(Mailer.selector_template_bind_sender_name).val();
	},

	clearSenderName: function(){
		this.setSenderName('');
	},

	setSubject: function(subject){
		return $(Mailer.selector_template_bind_subject).val(subject);
	},

	getSubject: function(){
		return $(Mailer.selector_template_bind_subject).val();
	},

	clearSubject: function(){
		this.setSubject('');
	},
	
	setContent: function(content){
		return $(Mailer.selector_template_bind_content).val(content);
	},

	getContent: function(){
		return $(Mailer.selector_template_bind_content).val();
	},

	clearContent: function(){
		this.setContent('');
	},

	isValid: function() {
		var valid = true;

		if (!Mailer.getSender().match(/^.*@.+\..{2,3}$/i)) {
			$(Mailer.selector_template_bind_sender).addClass('ui-state-error');
			valid = false;
		} else {
			$(Mailer.selector_template_bind_sender).removeClass('ui-state-error');
		}

		if (Mailer.getSenderName() == '') {
			$(Mailer.selector_template_bind_sender_name).addClass('ui-state-error');
			valid = false;
		} else {
			$(Mailer.selector_template_bind_sender_name).removeClass('ui-state-error');
		}

		if (Mailer.getSubject() == '') {
			$(Mailer.selector_template_bind_subject).addClass('ui-state-error');
			valid = false;
		} else {
			$(Mailer.selector_template_bind_subject).removeClass('ui-state-error');
		}
		
		if (Mailer.getContent() == '') {
			$(Mailer.selector_template_bind_content).addClass('ui-state-error');
			valid = false;
		} else {
			$(Mailer.selector_template_bind_content).removeClass('ui-state-error');
		}

		return valid;
	},

	setSend: function(send) {
		this._send = parseInt(send);

		$(Mailer.selector_mail_send).text(this._send+1);
	},

	clearSend: function() {
		this.setSend(0);
	},
	
	setCount: function(count) {
		this._count = parseInt(count);

		$(Mailer.selector_mail_count).text(this._count);
	},

	clearCount: function() {
		this.setCount(0);
	},
	
	getData: function() {
		// protoplasta ;) danych
		var data = {
			sender: Mailer.getSender(),
			sender_name: Mailer.getSenderName(),
			content: Mailer.getContent(),
			subject: Mailer.getSubject(),
			recipent: null
		};
		return data;
	},

	_sendInInterval: 4,

	setSendInInterval:function(interval) {
		this._sendInInterval = parseInt(interval);
	},

	getSendInInterval: function() {
		// ustawienie domyślnego interwału jeżeli ten jest niepoprawny
		return (this._sendInInterval > 0) ? this._sendInInterval : 4;
	},
	
	_count: 0,

	_send: 0,

	_start: 0,

	_sended: true,

	_interval: null,

	_stoped: false,

	isStarted: function(){
		return !this._stoped;
	},

	send: function() {
		this.clear();
		this.start();
	},

	start: function () {
		var self = this;

		// czy wszyskie pola są podane
		if (!Mailer.isValid()) {
			return false;
		}

		var list = Mailer.getMailList();

		self.setCount(list.length);

		// czy są wybrani nadawcy
		if (list.length < 1) {
			alert('Nie wybrano maili do wysłania');
			return false;
		}

		// uruchomiony
		Mailer._stoped = false;

		// Mailer.// console.log(1);
		
		Mailer._interval = setInterval(function() {
			// jeszcze wysyłanie jest w kolejce
			if (!Mailer._sended) {
				return;
			}
			// koniec starej kolejki, start nowej!
			else {
				Mailer._sended = false;
			}

			var list = Mailer.getMailList();
			
			var count = 0;
			var dataset = [];

			$('#debug').text($('#debug').text() + "\n _Statr:" + Mailer._start);
			$('#debug').text($('#debug').text() + "\n _Count:" + Mailer._count);

			for (var i = Mailer._start; i < Mailer._count; i++) {
				var data = Mailer.getData();

				// numer wysłanych
				Mailer._send = i;
				self.setSend(i);

				$('#debug').text($('#debug').text() + "\n _i:" + i);
				
				// wysyłanie w paczkach po .. x(10)
				if (++count > Mailer.getSendInInterval()) {
					break;
				} else {
					// tworzenie paczki
					data.recipent = list[i].value;
					dataset.push(data);
					
				}
			}

			// zapamietaj ostatni uzyty index
			// (+1) - bo od niego będziesz zaczybnać
			Mailer._start = Mailer._send+1;

			// wysyłanie paczki
			Mailer.send_(dataset);

			// przerwij wysyłanie
			if (Mailer._start >= Mailer._count) {
				Mailer.stop();
			}
		}, 1000);
	},
	
	stop: function() {
		Mailer._stoped = true;
		clearInterval(Mailer._interval);
	},

	send_: function(data) {
		$.ajax({
			url: Mailer.url_send,
			type: 'post',
			data: http_build_query(data),
			dataType: 'json',
			success: Mailer.onSuccessSend
		});
	},

	onSuccessSend: function(json){
		// pakiet wiadomości wysłany
		Mailer._sended = true;

		// powiększenie progresbara
		$(Mailer.selector_progressbar).progressbar({
			value: parseInt(Mailer._send+1/Mailer._count*100)
		});

		// wartośc wysłanych
		$(Mailer.selector_progressbar).progressbar('value', parseInt(Mailer._send+1/Mailer._count*100));

		// koniec rozsyłania kolejki.. dociągnij do 100%
		if (Mailer._stoped) {
			$(Mailer.selector_progressbar).progressbar('value', 100);
		}
	},

	getMailList: function() {
		var checked = $(Mailer.selector_mail_list).find(':checked').serializeArray();
		return checked;
	}
};

//Mailer. console = console;

Mailer.init();
$('#dialog').dialog({
	width:500,
	height:100,
	resizable: false,
	modal: true,
	title: 'Postęp rozsyłania maili',
	overlay: {
		backgroundColor: '#000',
		opacity: 0.5
	},
	buttons: {
		'Stop/Start': function() {
			Mailer.isStarted()
				? Mailer.stop()
				: Mailer.start();
		},
		'Anuluj wysyłanie maili': function() {
			Mailer.stop();
			Mailer.clear();
			Mailer.clearData();
			$(this).dialog('close');
		}
	}
}).dialog('close');

$('.send-mails a').click(function(){
	if (Mailer.isValid()) {
		$('#dialog').dialog('open');
		Mailer.send();
	}
	return false;
});

$('.reset a').click(function(){
	Mailer.clear();
	Mailer.clearData();
	return false;
});


$('#check-all').click(function(){
	$('#mail-list :checkbox').attr('checked' ,true);
});
$('#check-none').click(function(){
	$('#mail-list :checkbox').attr('checked' ,false);
});

$('#mail-reload a').click(function(){
	Mailer.initMail();
	return false;
});
$('#mail-template-reload a').click(function(){
	Mailer.initTemplate();
	return false;
});

})(jQuery);
 --></script>